package com.zyzd.commontools.image;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.zyzd.commontools.CommonTools;
import com.zyzd.commontools.cache.ACache;
import com.zyzd.commontools.file.FileUtils;
import com.zyzd.commontools.log.TLog;
import com.zyzd.commontools.screen.TDevice;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 李宗源 on 2017/3/9.
 */

public class ImageUtil {

    private static Map<String, Bitmap> bitmapMap = new HashMap<>();

    /**
     * 加载屏幕尺寸的图片
     *
     * @param context
     * @param imageView
     * @param resId
     * @param tag
     */
    public static void loadBgImage(final Context context, final ImageView imageView, final int resId, final String tag) {
        loadBgImage(context, imageView, resId, tag, TDevice.getWidth(), TDevice.getHeight());
    }

    /**
     * 加载指定尺寸的图片
     *
     * @param context
     * @param imageView
     * @param resId
     * @param tag
     * @param width
     * @param height
     */
    public static void loadBgImage(final Context context, final ImageView imageView, final int resId, final String tag, final int width, final int height) {
        final Bitmap bitmap = bitmapMap.get(tag);

        if (bitmap != null) {
            setImageBitmap(imageView, bitmap);
            return;
        }

        new AsyncTask<Object, Void, Bitmap>() {

            @Override
            protected Bitmap doInBackground(Object... args) {
                return ACache.get(CommonTools.getContext()).getAsBitmap(tag);
            }

            protected void onPostExecute(Bitmap image) {

                if (image != null) {
                    setImageBitmap(imageView, image);
                    bitmapMap.put(tag, image);
                } else {
                    loadImageByGlide(context, imageView, resId, tag, width, height);
                }

            }
        }.execute();
    }

    /**
     * 给imageView设置bitmap
     *
     * @param imageView
     * @param bitmap
     */
    private static void setImageBitmap(ImageView imageView, Bitmap bitmap) {
        if (imageView != null) {
            imageView.setImageBitmap(bitmap);
        }
    }

    /**
     * 从资源文件中加载图片，并进行指定尺寸处理后保存到本地
     *
     * @param context
     * @param imageView
     * @param resId
     * @param tag
     * @param width
     * @param height
     */
    private static void loadImageByGlide(final Context context, final ImageView imageView, int resId, final String tag, int width, int height) {
        Glide.with(CommonTools.getContext()).load(resId).asBitmap().override(width, height).into(new SimpleTarget<Bitmap>() {

            @Override
            public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                if (bitmap != null) {
                    setImageBitmap(imageView, bitmap);
                    bitmapMap.put(tag, bitmap);
                    saveBg(context, bitmap, tag);
                }
            }
        });
    }

    /**
     * 保存到本地
     *
     * @param context
     * @param bitmap
     * @param tag
     */
    private static void saveBg(final Context context, final Bitmap bitmap, final String tag) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ACache.get(context).put(tag, bitmap);
            }
        }).start();
    }

    /**
     * 图片压缩，当图片大于1000可就进行压缩加载然后再上传
     *
     * @param fromFile
     * @param quality
     * @return
     */
    public static File imageZoom(String fromFile, int quality) {
        try {
            File file = new File(fromFile);
            if (file.length() > 1000 * 1024) {
                Bitmap bitmap = decodeThumbBitmapForFile(fromFile, 600, 600);
                file = new File(FileUtils.getCacheDirectory("img"), FileUtils.getName("zoom_" + fromFile));
                FileOutputStream out = new FileOutputStream(file);
                if (bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)) {
                    out.flush();
                    out.close();
                }
                if (!bitmap.isRecycled()) {
                    bitmap.recycle();//记得释放资源，否则会内存溢出
                }
            }
            TLog.d("zyzd", "ImageUtil>>imageZoom-file.length-> " + file.length());
            return file;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 根据View(主要是ImageView)的宽和高来获取图片的缩略图
     *
     * @param path
     * @param viewWidth
     * @param viewHeight
     * @return
     */
    private static Bitmap decodeThumbBitmapForFile(String path, int viewWidth, int viewHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        //设置为true,表示解析Bitmap对象，该对象不占内存
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        //设置缩放比例
        options.inSampleSize = computeScale(options, viewWidth, viewHeight);

        //设置为false,解析Bitmap对象加入到内存中
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(path, options);
    }


    /**
     * 根据View(主要是ImageView)的宽和高来计算Bitmap缩放比例。默认不缩放
     *
     * @param options
     * @param viewWidth
     * @param viewHeight
     */
    private static int computeScale(BitmapFactory.Options options, int viewWidth, int viewHeight) {
        int inSampleSize = 1;
        if (viewWidth == 0 || viewHeight == 0) {
            return inSampleSize;
        }
        int bitmapWidth = options.outWidth;
        int bitmapHeight = options.outHeight;

        //假如Bitmap的宽度或高度大于我们设定图片的View的宽高，则计算缩放比例
        if (bitmapWidth > viewWidth || bitmapHeight > viewWidth) {
            int widthScale = Math.round((float) bitmapWidth / (float) viewWidth);
            int heightScale = Math.round((float) bitmapHeight / (float) viewHeight);

            //为了保证图片不缩放变形，我们取宽高比例最小的那个
            inSampleSize = widthScale < heightScale ? widthScale : heightScale;
        }
        return inSampleSize;
    }

}
